<script setup lang="ts">
import type { TableInstance } from 'element-plus'
import { Back, DataBoard } from '@element-plus/icons-vue'
import type { IndicatorInfo } from '@/types'

withDefaults(
  defineProps<{
    loading: boolean
    tableData: IndicatorInfo[]
  }>(),
  {},
)

const checked = shallowRef<IndicatorInfo[]>([])
const modelType = ref('1')
const operateType = ref(0)
const tableRef = ref<TableInstance>()
const showCheckbox = ref(false)

const emitter = inject<any>('model-configs:emitter')

interface ModelConfig {
  modelType: string
  pointId?: number
  indicatorIds: (number | undefined)[]
}
async function bindData(data: Required<ModelConfig>) {
  try {
    const { code } = await modelConfigApi.addModelConfig(
      data,
    )
    if (code === 200) {
      ElMessage.success('保存成功')
    }
  }
  catch (e) {}
}
async function unbindData(data: ModelConfig) {
  try {
    const { code } = await modelConfigApi.updateModelConfig(
      data,
    )
    if (code === 200) {
      ElMessage.success('保存成功')
    }
  }
  catch (e) {}
}

function clickBack() {
  operateType.value = 0
  showCheckbox.value = false
  emitter?.emit('toggle-show:tree', true)
}
function clickSave() {
  console.log('checked: ', checked.value)
  const indicator = checked.value[0]
  const pointId = indicator?.id
  const indicatorIds = checked.value.map(v => v.id)
  const mType = modelType.value

  // console.log(`isBinding: ${isBinding.value}`);
  // console.log(`pointId: ${pointId}`);
  // console.log(`modelType: ${modelType}`);
  // console.log(`indicatorIds: ${indicatorIds}`);
  const isBinding = operateType.value === 1
  const isUnbinding = operateType.value === 2
  if (isBinding) {
    if (
      pointId === undefined
      || indicatorIds.length === 0
    ) {
      ElMessage.error('请勾选指标进行应用建模')
      return
    }
    // console.log('bind');
    bindData({
      pointId,
      modelType: mType,
      indicatorIds,
    })
  }
  else if (isUnbinding) {
    // console.log('unbind');
    unbindData({
      modelType: mType,
      indicatorIds,
    })
  }
}

async function clickBindAppModal() {
  operateType.value = 1
  showCheckbox.value = true
  emitter?.emit('toggle-show:tree', true)
}
async function clickUnbindAppModal() {
  operateType.value = 2
  showCheckbox.value = true
  emitter?.emit('toggle-show:tree', false)
  emitter?.emit('query:model-configs', {
    modelType: modelType.value,
    callback: () => {
      tableRef.value?.toggleAllSelection?.()
    },
  })
}
</script>

<template>
  <div class="view-manage relative">
    <ElForm v-if="operateType > 0" inline class="mb-0">
      <ElFormItem>
        <div class="align-center flex" @click="clickBack">
          <ElIcon class="margin-right-xs">
            <Back />
          </ElIcon>
          返回
        </div>
      </ElFormItem>
      <ElFormItem label="应用模型">
        <DictionaryPicker
          v-model="modelType"
          code="YING_YONG_MO_XING"
        />
      </ElFormItem>
      <ElFormItem>
        <ElButton type="primary" @click="clickSave">
          保存
        </ElButton>
      </ElFormItem>
    </ElForm>
    <div v-else class="flex-incompressible flex">
      <ElButton
        style="margin-left: auto"
        plain
        type="primary"
        :icon="DataBoard"
        @click="clickBindAppModal"
      >
        绑定应用模型
      </ElButton>
      <ElButton
        plain
        type="danger"
        :icon="DataBoard"
        @click="clickUnbindAppModal"
      >
        解绑应用模型
      </ElButton>
    </div>
    <ElTable
      ref="tableRef"
      v-loading="loading"
      :data="tableData"
      align="center"
      show-overflow-tooltip
      style="width: 100%"
      @selection-change="e => (checked = e)"
    >
      <ElTableColumn
        v-if="showCheckbox"
        fixed
        type="selection"
        width="80"
      />
      <ElTableColumn prop="indicatorName" label="指标名称">
        <template #default="{ row }">
          <ElLink type="primary" :underline="false">
            {{ row.indicatorName }}
          </ElLink>
        </template>
      </ElTableColumn>
      <!-- <ElTableColumn
        label="是否虚拟指标"
        :show-overflow-tooltip="false"
      >
        <template #default="{ row }">
          <ElTag v-if="!row.isVirtually" effect="light">
            普通指标
          </ElTag>
          <ElTag v-else type="danger" effect="light">
            虚拟指标
          </ElTag>
        </template>
      </ElTableColumn> -->
      <ElTableColumn
        label="指标类别"
        prop="indicatorTypeName"
      />
      <ElTableColumn
        label="测点点位号"
        prop="indicatorCode"
      />
      <ElTableColumn prop="unitName" label="指标单位" />
      <template #empty>
        <TableEmpty />
      </template>
    </ElTable>
  </div>
</template>

<style scoped>
.mb-0 :deep(.el-form-item) {
  margin-bottom: 0 !important;
}
</style>
